package com.est.dase;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
/**
 *
 * @author Fernando Geraldes, Jaime Santos, Jorge Silva
 *
 */

public class MyLocation {

	LocationManager lm;
	boolean gps_enabled=false;
	boolean network_enabled=false;

	public Location getLocation(Context context)
	{
		Location location = null;

		if(lm==null)
			lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

		try{
			gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
		}catch(Exception ex){}
		try{
			network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		}catch(Exception ex){}

		if(!gps_enabled && !network_enabled)
			location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

		if(gps_enabled){
			lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
			location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		}
		if(network_enabled){
			lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
			location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		}

		return location;
	}

	LocationListener locationListenerGps = new LocationListener() {
		public void onLocationChanged(Location location) {
			lm.removeUpdates(this);
			lm.removeUpdates(locationListenerNetwork);
		}
		public void onProviderDisabled(String provider) {}
		public void onProviderEnabled(String provider) {}
		public void onStatusChanged(String provider, int status, Bundle extras) {}
	};

	LocationListener locationListenerNetwork = new LocationListener() {
		public void onLocationChanged(Location location) {
			lm.removeUpdates(this);
			lm.removeUpdates(locationListenerGps);
		}
		public void onProviderDisabled(String provider) {}
		public void onProviderEnabled(String provider) {}
		public void onStatusChanged(String provider, int status, Bundle extras) {}
	};

}
